#include"lst_timer.h"

sort_time_lst::sort_time_lst(){
    head = NULL;
    tail = NULL;
}
sort_time_lst::~sort_time_lst(){
    util_timer* temp = head;
    while(temp!=NULL){
        head = temp->next;
        delete temp;
        temp = head;
 
    }
}

void sort_time_lst::add_timer(util_timer* timer) {
    if(!timer){
        return ;
    }
    if(!head){
        head = tail = timer;
        return;
    }
    if(timer->expire<=head->expire){
        head->prev = timer;
        timer->next = head;
        head = timer;
        return;
    }
    add_timer(timer,head);
}

//某个连接在某个时刻被访问，应适当延长等待时间
void sort_time_lst::adjust_timer(util_timer* timer){
    if(!timer){
        return;
    }
    if(timer->next==NULL||timer->expire<=timer->next->expire){
        return;
    }
    //更改节点是头节点
    if(timer==head){
        head = timer->next;
        timer->next = NULL;
        head->prev = NULL;
        add_timer(timer,head);
    }
    else{
        timer->prev->next = timer->next;
        timer->next->prev = timer->prev;
        timer->next = NULL;
        timer->prev = NULL;
        add_timer(timer,head);
    }
}

void sort_time_lst::del_timer(util_timer* timer){
    if(!timer){
        return;
    }
    if(timer==head&&timer==tail){
        delete timer;
        head = NULL;
        tail = NULL;
        return;
    }
    if(timer==head){
        head = head->next;
        head->prev = NULL;
        delete timer;
        return;
    }
    if(timer == tail){
        tail = timer->prev;
        tail->next = NULL;
        delete timer;
        return;
    }
    timer->prev->next = timer->next;
    timer->next->prev = timer->prev;
    delete timer;

}


//对链表遍历，找出超时事件进行处理，到时后，执行定时器回调函数
void sort_time_lst::tick(){
    if(!head){
        return;
    }
    cout<<"timer tick"<<endl;
    util_timer* temp = head;
    int cur_time = time(NULL);
    while(temp!=NULL){
        if(cur_time<temp->expire){
            break;
        }
        temp->cb_func(temp->user_data); //其实就是清除链表，关闭文件描述符
        //清除链表下面在做
        head = temp->next;
        if(head){
            head->prev = NULL;
        }
        delete temp;
        temp = head;
    }
}

//要添加的计时器不是链表的头部,重载
void sort_time_lst::add_timer(util_timer* timer,util_timer* head){
    util_timer* prev = head;
    util_timer* next = head->next;
    while(next!=NULL){
        if(timer->expire <= next->expire){
            prev->next = timer;
            timer->prev = prev;
            timer->next = next;
            next->prev = timer;
            break;
        }
        prev = prev->next;
        next = next->next;
    } 
    if(next==NULL){
        timer->next = NULL;
        timer->prev = prev;
        prev->next = timer;
        tail = timer;
    }
}